////////////////////
//Audio functions
////////////////////

PRESENCE.AUDIO = (function(P,$,undefined){
		
	//Audio variables
	var audio_path = '<%=image_path("chat")%>';
	var onMessageAudio;
	
	var html5_audiotypes=[
	  ["mp3","audio/mpeg"],
	  //["mp4","audio/mp4"],
	  //["ogg","audio/ogg"],
	  ["wav","audio/wav"]
	]
	
	
	var init = function(){
    //Init all audio files
    initSound("onMessageAudio");
  }
	
	
	var initSound = function(sound){
  
    //Check support for HTML5 audio
    var html5audio=document.createElement('audio')
  
    if (html5audio.canPlayType){ 
      path = audio_path + "/" + sound;
      window[sound] = new Audio();

	    for(i=0; i<html5_audiotypes.length; i++){
	      if (window[sound].canPlayType(html5_audiotypes[i][1])) {
	        var source= document.createElement('source');
	        source.type= html5_audiotypes[i][1];
	        source.src= path + '.' + html5_audiotypes[i][0];
	        window[sound].addEventListener('ended', endSoundListener);
	        window[sound].appendChild(source);
	      } 
	    }
    } else {
    //Browser doesn't support HTML5 audio
    }
  }


  function endSoundListener(){ }


	function playSound(sound){
	  if (window[sound]!=null){
	    window[sound].play();
	  } else {
	    //Fallback option: When browser doesn't support HTML5 audio
	    $('body').append('<embed src="' + audio_path + '/' + sound + '.mp3" autostart="true" hidden="true" loop="false">');
	  }
	}

	function initAndPlaySound(sound){
	    initSound(sound);
	    playSound(sound);
	}


	function mustPlaySoundForChatWindow(chatBox){
	  //Deny conditions
	  if(PRESENCE.XMPPClient.getUserStatus() == "dnd"){
	    return false;
	  }
	  
	  //Accept conditions
	  if (!PRESENCE.UTILITIES.getChatFocus()){
	    return true;
	  }
	  
	  //Default action
	  return false
	}
	
  return {
    init                        : init,
		mustPlaySoundForChatWindow  : mustPlaySoundForChatWindow,
    playSound                   : playSound
  };

}) (PRESENCE, jQuery);